﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

namespace AntiObesity.DatabaseAccess
{
    public abstract class DataBaseBase : IDB
    {
        protected abstract string GetConnectionString();

        public SqlConnection GetConnection()
        {
            var connectionString = GetConnectionString();
            var conn = new SqlConnection(connectionString);
            return conn;
        }

        public SqlDataReader ExecuteForReader(SqlConnection connection, string sql)
        {
            if (connection.State == ConnectionState.Closed)
                connection.Open();

            var cmd = new SqlCommand(sql, connection);
            return cmd.ExecuteReader();
        }

        public void Execute(SqlConnection connection, string sql)
        {
            if (connection.State == ConnectionState.Closed)
                connection.Open();

            var cmd = new SqlCommand(sql, connection);
            cmd.ExecuteNonQuery();
        }

        public int ExecuteForInt(SqlConnection connection, string sql)
        {
            if (connection.State == ConnectionState.Closed)
                connection.Open();

            var cmd = new SqlCommand(sql, connection);
            return Convert.ToInt32(cmd.ExecuteScalar());
        }

        public float ExecuteForFloat(SqlConnection connection, string sql)
        {
            if (connection.State == ConnectionState.Closed)
                connection.Open();

            var cmd = new SqlCommand(sql, connection);
            var result = cmd.ExecuteScalar();
            if (Convert.IsDBNull(result))
                return 0;
            return (float)Convert.ToDouble(result);
        }

        public DateTime ExecuteForDate(SqlConnection connection, string sql)
        {
            if (connection.State == ConnectionState.Closed)
                connection.Open();

            var cmd = new SqlCommand(sql, connection);
            var result = cmd.ExecuteScalar();
            if (Convert.IsDBNull(result))
                return DateTime.MinValue;
            return Convert.ToDateTime(result);
        }

    }
}
